let cmr;
let rec;
// let audioPlayer;
// 请求权限
let requestPermissions = function (params) {
  if (window.plus) {
    plus.android.requestPermissions(params.type, function (e) {
      if (e.deniedAlways.length > 0) { //权限被永久拒绝
        // 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启
        console.log('Always Denied!!! ' + e.deniedAlways.toString());
      }
      if (e.deniedPresent.length > 0) { //权限被临时拒绝
        // 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
        console.log('Present Denied!!! ' + e.deniedPresent.toString());
      }
      if (e.granted.length > 0) { //权限被允许
        console.log(`${params.type.join(",")}已被允许`);
      }
      params.success ? params.success() : null;
    }, function (e) {
      params.fail ? params.fail(e) : null;
    })
  }
};

//使用示例
//国测局坐标(火星坐标,比如高德地图在用),百度坐标,wgs84坐标(谷歌国外以及绝大部分国外在线地图使用的坐标)
//百度经纬度坐标转国测局坐标
// let bd09togcj02 = coordtransform.bd09togcj02(116.404, 39.915);
// //国测局坐标转百度经纬度坐标
// let gcj02tobd09 = coordtransform.gcj02tobd09(116.404, 39.915);
// //wgs84转国测局坐标
// let wgs84togcj02 = coordtransform.wgs84togcj02(116.404, 39.915);
// //国测局坐标转wgs84坐标
// let gcj02towgs84 = coordtransform.gcj02towgs84(116.404, 39.915);

// //百度经纬度坐标转wgs84坐标
// let bd09towgs84 = coordtransform.bd09towgs84(lng, lat);
// //wgs84坐标转百度经纬度坐标
// let wgs84tobd09 = coordtransform.wgs84tobd09(lng, lat);



(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.coordtransform = factory();
  }
}(this, function () {
  //定义一些常量
  let x_PI = 3.14159265358979324 * 3000.0 / 180.0;
  let PI = 3.1415926535897932384626;
  let a = 6378245.0;
  let ee = 0.00669342162296594323;
  /**
   * 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换
   * 即 百度 转 谷歌、高德
   * @param bd_lon
   * @param bd_lat
   * @returns {*[]}
   */
  let bd09togcj02 = function bd09togcj02(bd_lon, bd_lat) {
    bd_lon = +bd_lon;
    bd_lat = +bd_lat;
    let x = bd_lon - 0.0065;
    let y = bd_lat - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_PI);
    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_PI);
    let gg_lng = z * Math.cos(theta);
    let gg_lat = z * Math.sin(theta);
    return [gg_lng, gg_lat]
  };

  /**
   * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
   * 即谷歌、高德 转 百度
   * @param lng
   * @param lat
   * @returns {*[]}
   */
  let gcj02tobd09 = function gcj02tobd09(lng, lat) {
    lat = +lat;
    lng = +lng;
    let z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
    let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
    let bd_lng = z * Math.cos(theta) + 0.0065;
    let bd_lat = z * Math.sin(theta) + 0.006;
    return [bd_lng, bd_lat]
  };

  /**
   * WGS84转GCj02
   * @param lng
   * @param lat
   * @returns {*[]}
   */
  let wgs84togcj02 = function wgs84togcj02(lng, lat) {
    lat = +lat;
    lng = +lng;
    if (out_of_china(lng, lat)) {
      return [lng, lat]
    } else {
      let dlat = transformlat(lng - 105.0, lat - 35.0);
      let dlng = transformlng(lng - 105.0, lat - 35.0);
      let radlat = lat / 180.0 * PI;
      let magic = Math.sin(radlat);
      magic = 1 - ee * magic * magic;
      let sqrtmagic = Math.sqrt(magic);
      dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
      dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
      let mglat = lat + dlat;
      let mglng = lng + dlng;
      return [mglng, mglat]
    }
  };

  /**
   * GCJ02 转换为 WGS84
   * @param lng
   * @param lat
   * @returns {*[]}
   */
  let gcj02towgs84 = function gcj02towgs84(lng, lat) {
    lat = +lat;
    lng = +lng;
    if (out_of_china(lng, lat)) {
      return [lng, lat]
    } else {
      let dlat = transformlat(lng - 105.0, lat - 35.0);
      let dlng = transformlng(lng - 105.0, lat - 35.0);
      let radlat = lat / 180.0 * PI;
      let magic = Math.sin(radlat);
      magic = 1 - ee * magic * magic;
      let sqrtmagic = Math.sqrt(magic);
      dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
      dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
      let mglat = lat + dlat;
      let mglng = lng + dlng;
      return [lng * 2 - mglng, lat * 2 - mglat]
    }
  };

  /**
   * 百度坐标系 (BD-09) 转换为 WGS84
   * @param lng
   * @param lat
   * @returns {*[]}
   */
  let bd09towgs84 = function bd09towgs84(bd_lon, bd_lat) {
    //百度经纬度坐标转国测局坐标
    let bd09togcj02_arr = coordtransform.bd09togcj02(bd_lon, bd_lat);
    //国测局坐标转wgs84坐标
    let gcj02towgs84_arr = coordtransform.gcj02towgs84(bd09togcj02_arr[0], bd09togcj02_arr[1]);
    return [gcj02towgs84_arr[0], gcj02towgs84_arr[1]]
  };

  /**
   * WGS84 转换为 百度坐标系 (BD-09)
   * @param lng
   * @param lat
   * @returns {*[]}
   */
  let wgs84tobd09 = function wgs84tobd09(lng, lat) {
    //wgs84转国测局坐标
    let wgs84togcj02_arr = coordtransform.wgs84togcj02(lng, lat);
    //国测局坐标转百度经纬度坐标
    let gcj02tobd09_arr = coordtransform.gcj02tobd09(wgs84togcj02_arr[0], wgs84togcj02_arr[1]);
    return [gcj02tobd09_arr[0], gcj02tobd09_arr[1]]
  };

  let transformlat = function transformlat(lng, lat) {
    lat = +lat;
    lng = +lng;
    let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math
      .abs(lng));
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
    ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
    return ret
  };

  let transformlng = function transformlng(lng, lat) {
    lat = +lat;
    lng = +lng;
    let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(
      lng));
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
    ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
    return ret
  };

  /**
   * 判断是否在国内，不在国内则不做偏移
   * @param lng
   * @param lat
   * @returns {boolean}
   */
  let out_of_china = function out_of_china(lng, lat) {
    lat = +lat;
    lng = +lng;
    // 纬度3.86~53.55,经度73.66~135.05
    return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
  };

  return {
    bd09togcj02: bd09togcj02,
    gcj02tobd09: gcj02tobd09,
    wgs84togcj02: wgs84togcj02,
    gcj02towgs84: gcj02towgs84,
    bd09towgs84: bd09towgs84,
    wgs84tobd09: wgs84tobd09
  }
}));
window.qmSdk = {

  ready: function (callback) {
    if (window.plus) {
      callback();
    } else {
      document.addEventListener('plusready', callback);
    }
  },

  // 修改导航栏
  setNavigation: function (params) {
    window.qmSdk.ready(function () {
      let wv = window.plus.webview.currentWebview();
      let tn = wv.getTitleNView();
      if (params.hidden != 1) {
        let style = {};
        if (params.backgroundImage && params.backgroundImage.startsWith("http")) {
          var dtask = plus.downloader.createDownload(params.backgroundImage, {}, function (d, status) {
            // 下载完成
            style = {
              titleNView: {
                titleText: params.title,
                titleColor: params.titleColor,
                titleSize: params.fontSize,
                backgroundColor: params.backgroundColor,
                backgroundImage: params.backgroundImage || "",
              }
            };
            if (status == 200) {
              style.titleNView.backgroundImage = d.filename;
            }
            //}
            wv.setStyle(style);
            if (tn && !tn.isVisible()) {
              tn.show();
            }
          });
          dtask.start();
        } else {
          // if (params.type == 2) {
          //   style = {
          //     titleNView: {
          //       subtitleText: params.title,
          //       subtitleColor: params.titleColor,
          //       subtitleSize: params.fontSize,
          //       backgroundColor: params.backgroundColor,
          //       backgroundImage: params.backgroundImage,
          //     }
          //   };
          // } else {
          style = {
            titleNView: {
              titleText: params.title,
              titleColor: params.titleColor,
              titleSize: params.fontSize,
              backgroundColor: params.backgroundColor,
              backgroundImage: params.backgroundImage || "",
            }
          };
          //}
          wv.setStyle(style);
          if (tn && !tn.isVisible()) {
            tn.show();
          }
        }
      } else if (tn) {
        tn.close();
      }
      params.success ? params.success() : null;
    });
  },

  //打开web页面
  openLink: function (params) {
    try {
      let mapp = {
        appCode: params.title || Math.random(),
        appName: params.title || "",
        appLink: params.url,
        preloading: 0,
        isLogin: 1,
        cssText: "",
        listenResourceJs: "",
        backJS: "",
        isTitleBar: params.hidden != "1",
        publicKey: "",
        privateKey: "",
      };
      plus.webview.getLaunchWebview().evalJS('vue.$framework.miniApp.open(' + JSON.stringify(mapp) + ',null,"white");');
      params.success ? params.success() : null;
    } catch (error) {
      params.fail ? params.fail(error) : null;
    }
  },

  //预览文件
  scanFile: function (params) {
    localStorage.setItem('windowparentelectron',JSON.stringify(window.parent.electron))
    if(window.parent.electron){
      let obj = JSON.stringify(params)
      window.parent.electron.ipcRenderer.send("excel-window",obj);
      return
  }
  try {
      localStorage.setItem('scanFileparams',JSON.stringify(params))
      var fileType = params.filename.substring(params.filename.lastIndexOf(".") + 1);
      if (["png", "jpg","jpeg"].includes(fileType)) {
        params.imgs = [params.downloadurl];
        window.qmSdk.showPhotos(params);
      } else {
        var view = plus.webview.create('_www/static/onlyoffice/viewer.html', "文档预览", {
          popGesture: 'none',
          scrollIndicator: 'none',
          scalable: false,
          backButtonAutoControl: 'close',
        }, {
          option: {
            title: params.filename,
            fileType: fileType,
            url: params.downloadurl
          },
          user: plus.webview.currentWebview().user
        });
        view.show("slide-in-bottom");
      }
      params.success ? params.success() : null;
    } catch (error) {
      params.fail ? params.fail(error) : null;
    }
  },

  // 获取Token
  getToken: function (params) {
    try {
      params.success ? params.success({
        token: this.plus.webview.currentWebview().miniToken
      }) : null;
    } catch (err) {
      params.fail ? params.fail(err) : null;
    }

  },

  // 获取当前登陆用户信息
  getSessionStorage(params) {
    try {
      params.success ? params.success(this.plus.webview.currentWebview().user) : null;
    } catch (err) {
      params.fail ? params.fail(err) : null;
    }
  },

  // 刷新登陆 预留空方法
  reStartLogin: function () {},

  // 退出登陆 预留空方法
  logout: function () {
    this.$framework.account.logout();
  },


  // 相机权限
  getCameraAuth: function (params) {
    params.type = ["android.permission.CAMERA"];
    requestPermissions(params);
  },
  // 麦克风权限
  getMicrophoneAuth: function (params) {
    params.type = ["android.permission.RECORD_AUDIO"];
    requestPermissions(params);
  },
  // 日历权限
  getCalendarsAuth: function (params) {
    params.type = ["android.permission.WRITE_CALENDAR"];
    requestPermissions(params);
  },
  // 蓝牙权限
  getBluetoothAuth: function (params) {
    params.type = [
      "android.permission.BLUETOOTH",
      "android.permission.BLUETOOTH_ADMIN",
    ];
    requestPermissions(params);
  },
  // 通讯录权限
  getAddressBook: function (params) {
    params.type = [
      "android.permission.READ_CONTACTS",
      "android.permission.WRITE_CONTACTS",
    ];
    requestPermissions(params)
  },
  // 定位权限
  getLocationAuth: function (params) {
    params.type = [
      "android.permission.ACCESS_COARSE_LOCATION",
      "android.permission.ACCESS_FINE_LOCATION",
    ];
    requestPermissions(params);
  },
  // 存储权限 安卓
  getStorageAuth: function (params) {
    params.type = [
      "android.permission.WRITE_EXTERNAL_STORAGE",
      "android.permission.READ_EXTERNAL_STORAGE",
      // "android.permission.MANAGE_EXTERNAL_STORAGE",
    ];
    requestPermissions(params);
  },


  // 原生暂存 H5 数据
  saveH5Data: function (params) {
    try {
      if (window.plus) {
        params.value
        plus.storage.setItem(params.key, params.value);
      } else {
        window.localStorage.setItem(params.key, params.value);
      }
      params.success ? params.success() : null;
    } catch (e) {
      //TODO handle the exception
      params.fail ? params.fail(e) : null;
    }
  },

  // 读取 H5 数据
  getH5Data: function (params) {
    try {
      let value;
      if (window.plus) {
        value = plus.storage.getItem(params.key);
      } else {
        value = window.localStorage.getItem(params.key);
      }
      params.success ? params.success(value) : null;
    } catch (e) {
      params.fail ? params.fail(e) : null;
    }
  },

  // 获取位置信息
  getLocation: function (params) {
    if (window.plus) {
      plus.geolocation.getCurrentPosition(success => {
        params.success ? params.success(success) : null;
        console.log(JSON.stringify(success));
      }, error => {
        params.fail ? params.fail(error) : null;
        console.log(JSON.stringify(error));
      }, {
        coordsType: "bd09ll",
        enableHighAccuracy: true,
        timeout: 2000,
      });
    }
  },

  // 调用导航
  navigationto: function (params) {
    try {
      let lng = params.longitude; //目标经度
      let lat = params.latitude; //目标纬度
      //把百度坐标系bd09转国测局坐标系wgs84
      let sopt = coordtransform.bd09towgs84(lng, lat);
      //经测试腾讯地图必须使用火星坐标系gcj02，顾单独转换
      let coordQQ = coordtransform.bd09togcj02(lng, lat);
      //如果还知道其他地图的包名，也可以放这个数组里
      let mapsPackageNames = ['com.autonavi.minimap', 'com.baidu.BaiduMap', 'com.tencent.map'];
      //iOS与Android的判断第三方程序不一样，Android是包名，iOS是action属性（Scheme）
      let iosURLTypes = ['iosamap://', 'baidumap://', 'qqmap://'];
      if (plus.os.name == "iOS") {
        mapsPackageNames = iosURLTypes
      };
      operationAfterCheckInstall(mapsPackageNames, function (res) { //res(object)
        // alert(JSON.stringify(res))
        let m = 0,
          gotoUrl = ""; //m:记录本机地图app个数，gotoUrl：记录实际直接跳转地址
        let btnArray = []; //实际显示按钮数组
        let btnTitle = ["使用高德地图导航", "使用百度地图导航", "使用腾讯地图导航"];
        let urlArray = []; //实际显示跳转地址数组
        //百度api文档：http://lbsyun.baidu.com/index.php?title=uri/api/android
        //高德api文档：https://lbs.amap.com/api/amap-mobile/guide/ios/route
        //腾讯api文档：https://lbs.qq.com/webApi/uriV1/uriGuide/uriMobileRoute
        let andrUrl = [
          "amapuri://route/plan/?slat=&slon=&dlat=" + sopt[1] + "&dlon=" + sopt[0] +
          "&dev=1&t=0",
          "baidumap://map/direction?origin=&destination=" + sopt[1] + "," + sopt[0] +
          "&title=" + params.address + "&content=1111111111" +
          "&coord_type=wgs84&mode=driving&src=andr.baidu.openAPIdemo",
          "qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=" + coordQQ[
            1] + "," + coordQQ[0] + "&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"
        ]
        let iosUrl = [
          "iosamap://path?sourceApplication=applicationNameslat=&slon=&dlat=" + sopt[1] +
          "&dlon=" + sopt[0] + "&dev=1&t=0",
          "baidumap://map/direction?origin=&destination=" + sopt[1] + "," + sopt[0] +
          "&coord_type=wgs84&mode=driving&src=ios.baidu.openAPIdemo",
          "qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=" + coordQQ[
            1] + "," + coordQQ[0] + "&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"
        ]
        //根据手机型号确定跳转数组let
        if (plus.os.name == "iOS") {
          urlArray = iosUrl;
        } else {
          urlArray = andrUrl;
        }
        let gotoUrlArr = [];
        for (k in res) {
          // if (res[k]) {
          // m++;
          gotoUrl = urlArray[k];
          btnArray.push({
            title: btnTitle[k]
          })
          gotoUrlArr.push(urlArray[k])
          // }
        }
        // 如果手机有安装地图App，直接跳转
        if (res[parseInt(params.type) - 1]) {
          plus.runtime.openURL(gotoUrlArr[parseInt(params.type) - 1]);
          params.success ? params.success() : null;
        } else {
          params.fail ? params.fail(`您还未安装${btnTitle[parseInt(params.type)-1]},请前往应用市场下载`) :
            null;
        }
        //当只有一个地图APP时，直接跳转；不止一个时弹出原生选择框
        // if (m > 1) {
        // 	plus.nativeUI.actionSheet({
        // 		title: "请选择地图",
        // 		cancel: "取消",
        // 		buttons: btnArray
        // 	}, function(e) {
        // 		if (e.index > 0) { //=0:取消，1：百度，2：高德，3：腾讯
        // 			plus.runtime.openURL(gotoUrlArr[e.index - 1]);
        // 		}
        // 	});
        // } else {
        // 	plus.runtime.openURL(gotoUrl);
        // }


        // plus.maps.openSysMap(dst, name, src);//直接默认跳转第三方，无回调，已弃用
      }, function () {
        // alert("您未安装百度地图、高德地图、腾讯地图,请前往应用市场下载");
        params.fail ? params.fail("您未安装高德地图、百度地图、腾讯地图,请前往应用市场下载") : null;
      })


      //传入包名，检查手机上是否安装了这个应用
      function isInstall(packageName) {
        try {
          if (plus.os.name == "iOS") {
            let UIApplication = plus.ios.importClass("UIApplication");
            let NSURL = plus.ios.importClass("NSURL");

            let app = UIApplication.sharedApplication();
            let bdScheme = NSURL.URLWithString(packageName);
            let install = app.canOpenURL(bdScheme);

            plus.ios.deleteObject(bdScheme);
            plus.ios.deleteObject(app);
            return install
          } else {
            let main = plus.android.runtimeMainActivity();
            let packageManager = main.getPackageManager();
            let PackageManager = plus.android.importClass(packageManager);
            let packageinfo = packageManager.getPackageInfo(packageName, PackageManager
              .GET_ACTIVITIES)
            if (packageinfo) {
              return true;
            } else {
              return false;
            }
          }
        } catch (e) {
          return false;
        }
      }
      //批量传入包名，检查一系列应用是否安装，如果有任意一个安装了，就执行success，否认执行fai
      function operationAfterCheckInstall(mapsPackageNames, success, fail) {
        let res = mapsPackageNames.map(function (item) {
          return isInstall(item);
        })
        if (eval(res.join("||"))) {
          success(res);
        } else {
          fail();
        }
      }
    } catch (e) {
      params.fail(e);
    }
  },

  // 预览图片
  showPhotos: function (params) {
    try {
      if (window.plus) {
        plus.nativeUI.previewImage(params.imgs, {
          current: params.index || 0,
          loop: params.loop,
          onLongPress: params.onLongPress || null,
        });
        params.success ? params.success() : null;
      }
    } catch (error) {
      params.fail ? params.fail(error) : null;
    }
  },

  // 保存图片
  savePhotoToAlbum: function (params) {
    try {
      if (window.plus) {
        plus.gallery.save(params.downloadurl, params.success, params.fail)
      }
    } catch (e) {
      //TODO handle the exception
      params.fail(e);
    }
  },

  // 拨打电话
  call: function (params) {
    if (window.plus) {
      plus.device.dial(params.phone);
      params.success ? params.success() : null;
    }
    params.fail ? params.fail() : null;
  },

  // 文件上传
  fileUpload: function (params) {
    let uploaditem = params.uploaditem;
    let files = [];


    if (uploaditem.includes(1)) {
      console.log('包含1, 拍照');
      let cameraPhotoPath;
      new Promise((resolve, reject) => {
        qmSdk.camera({
          success: (res) => {
            res.captureImage(r => {
              // console.log(r);
              cameraPhotoPath = r;
              resolve();
            }, e => {
              console.log(JSON.stringify(e));
              reject(e);
            }, {
              filename: "_doc/camera/",
            });
          },
        })
      }).then(() => {
        console.log(cameraPhotoPath);
        // upload([cameraPhotoPath])
        plus.io.resolveLocalFileSystemURL(cameraPhotoPath, entry => {
          console.log(JSON.stringify(entry.toLocalURL()));
          upload([entry.toLocalURL()]);
        })

      }).catch(err => {
        params.fail ? params.fail(err) : null;
      })
    }

    if (uploaditem.includes(2)) {
      console.log("包含2, 从相册中选择");
      plus.gallery.pick(
        function (files) {
          // let filesData = files.files;
          upload(files.files);
        },
        function (err) {
          params.fail ? params.fail(err) : null;
        }, {
          animation: true,
          maximum: params.itemproperty.maximagescount,
          multiple: true
        });
    }

    // if (uploaditem.includes(3)) {
    // 	console.log("包含3, 从文件选择");
    // 	let btn = document.createElement("input");
    // 	btn.setAttribute("type", "file");
    // 	btn.setAttribute("multiple", "multiple");
    // 	btn.click();

    // 	btn.onchange = function(e) {
    // 		console.log(btn.files);
    // 	}
    // 	// plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
    // 	// 	console.log(fs);
    // 	// })
    // }

    if (uploaditem.includes(4)) {
      qmSdk.camera({
        success: res => {
          res.startVideoCapture(
            r => {
              console.log(r);
              upload([r])
            },
            err => {
              console.log(err);
              params.fail ? params.fail(err) : null;
            }, {
              filename: "_doc/camera/"
            }
          )
        },
        fail: err => {}
      })
    }


    function upload(files) {
      console.log(params.uploadurl);
      let task = plus.uploader.createUpload(
        params.uploadurl, {
          method: "POST"
        },
        (t, status) => {
          if (status === 200) {
            console.log("上传成功");
            params.success(t);
          } else {
            console.log("上传失败", status, JSON.stringify(t));
            params.fail ? params.fail(t) : null;
          }
        });

      let paramsKeys = Object.keys(params.params);
      for (let i in paramsKeys) {
        task.addData(paramsKeys[i], params.params[paramsKeys[i]]);
      }
      // return;
      for (let i = 0; i < files.length; i++) {
        console.log("添加文件");
        task.addFile(files[i], {});
      }
      task.start();
    }

  },

  // 语音识别
  startRecord: function (params) {
    let options = {
      engine: "baidu",
      timeout: 3000,
    }
    if (window.plus) {
      // let r = "";
      plus.speech.startRecognize(options, function (s) {
        console.log("识别成功 -->", s);
        // r += s;
        params.success(s)
      }, function (e) {
        params.fail(e)
      });

      // plus.speech.addEventListener("end", ()=> {
      // 	params.success(r);
      // });
    }
  },
  // 扫描二维码
  scanCodeCard: function (params) {
    try {
      var view = plus.webview.create('_www/static/libs/barcode.html', "扫一扫", {
        popGesture: 'none',
        scrollIndicator: 'none',
        scalable: false,
        backButtonAutoControl: 'true',
        titleNView: {
          type: 'float',
          backgroundColor: 'rgba(215,75,40,0.3)',
          titleText: '扫一扫',
          titleColor: '#FFFFFF',
          autoBackButton: true,
          buttons: [{
            text: '相册',
            fontSize: '18px',
            onclick: 'javascript:scanPicture()'
          }]
        }
      }, {});
      view.onclose = function () {
        if (window._scan_code_card_callback) {
          params.fail ? params.fail("用户关闭扫一扫页面") : null;
        }
      };
      view.show("slide-in-bottom");
      window._scan_code_card_callback = function (type, result, file) {
        params.success ? params.success({
          type: type,
          result: result,
          file: file
        }) : null;
        window._scan_code_card_callback = null;
      };
    } catch (error) {
      params.fail ? params.fail(error) : null;
    }
  },

  // 获取手机网络状态
  getNetworkConnectType: function (params) {
    if (window.plus) {
      let r = {};
      var types = {};
      types[plus.networkinfo.CONNECTION_UNKNOW] = "UNKNOWN";
      types[plus.networkinfo.CONNECTION_NONE] = "NO";
      types[plus.networkinfo.CONNECTION_ETHERNET] = "UNKNOWN"; // 有线
      types[plus.networkinfo.CONNECTION_WIFI] = "WIFI";
      types[plus.networkinfo.CONNECTION_CELL2G] = "MOBILE";
      types[plus.networkinfo.CONNECTION_CELL3G] = "MOBILE";
      types[plus.networkinfo.CONNECTION_CELL4G] = "MOBILE";
      r.connectType = types[plus.networkinfo.getCurrentType()];
      params.success(r);
    } else {
      params.fail ? params.fail() : null;
    }
  },

  // 开始录音
  startRecorder(params) {
    if (!rec) {
      rec = plus.audio.getRecorder();
    }
    rec.record({
      filename: "_doc/audio/"
    }, res => {
      params.success(res);
      // plus.io.resolveLocalFileSystemURL(res, (r)=> {
      // 	console.log("录音文件保存：", r);
      // },err=> {
      // 	console.log("err", err);
      // });
    }, err => {
      params.fail ? params.fail(e) : null;
    })

  },

  // 结束录音
  stopRecorder: function (params) {
    console.log(JSON.stringify(rec));
    if (window.plus) {
      if (!rec) {
        params.fail ? params.fail() : null;
        return;
      }
      rec.stop();
    } else {
      params.fail ? params.fail() : null;
    }
  },

  // 播放音频
  audioPlayer: function (params) {
    try {
      // if(!audioPlayer) {
      let audioPlayer = plus.audio.createPlayer(params.audio);
      params.success(audioPlayer);
      // }
    } catch (e) {
      params.fail ? params.fail(e) : null;
    }
  },

  // 拍照
  camera: function (params) {
    try {
      if (window.plus) {
        let c = plus.camera.getCamera(params.index);
        params.success(c);
      }
    } catch (e) {
      params.fail ? params.fail(e) : null;
    }
  },

  // 下载
  downloader: function (params) {
    try {
      let dtask = plus.downloader.createDownload(params.url, params.options, function (d, status) {
        // 下载完成
        if (status == 200) {
          console.log("Download success: " + d.filename);
          params.success(d);
        } else {
          console.log("Download failed: " + status);
          params.fail ? params.fail("下载失败: " + status) : null;
        }
      });
      dtask.start();
    } catch (e) {
      //TODO handle the exception
      params.fail ? params.fail(e) : null;
    }
  },

  // 指纹识别
  fingerprint: function (params) {
    try {
      if (window.plus) {
        if (plus.fingerprint) {
          if ('Android' == plus.os.name) {
            plus.nativeUI.showWaiting('指纹识别中...');
          }

          let errCount = 0;

          plus.fingerprint.authenticate(function () {
            //兼容Android平台关闭等待框
            plus.nativeUI.closeWaiting();
            params.success('指纹识别成功');
          }, function (e) {
            let errMsg = "";
            plus.nativeUI.closeWaiting();
            plus.nativeUI.showWaiting('指纹匹配失败，请重新输入');
            switch (e.code) {
              case e.AUTHENTICATE_MISMATCH:
                errMsg = '指纹匹配失败，请重新输入';
                break;
              case e.AUTHENTICATE_OVERLIMIT:
                //兼容Android平台关闭等待框
                plus.nativeUI.closeWaiting();
                plus.fingerprint.cancel();
                errMsg = '指纹识别失败次数超出限制，请使用其它方式进行认证';
                break;
              default:
                errMsg = '指纹识别失败(' + e.code + ')，请重试';
                break;
            }
            params.fail ? params.fail(errMsg) : null;


          }, "指纹识别中...");


        } else {
          console.log("请更新版本");
          params.fail ? params.fail("请更新版本") : null;
        }
      }
    } catch (e) {
      params.fail ? params.fail(e) : null;
    }
  },


  // 短信，彩信，邮件
  messaging: function (params) {
    if (window.plus) {
      let type;
      switch (params.type) {
        // 短信
        case "SMS":
          type = plus.messaging.TYPE_SMS;
          break;
          // 彩信
        case "MMS":
          type = plus.messaging.TYPE_MMS;
          break;
        case "EMAIL":
          type = plus.messaging.TYPE_EMAIL;
          break;
        default:
          type = plus.messaging.TYPE_SMS;
          break;
      }
      let msg = plus.messaging.createMessage(type);
      // to: 收件人信息
      msg.to = params.to;
      // cc: 抄送人信息
      msg.cc = params.cc;
      // bcc: 暗送人信息
      msg.bcc = params.bcc;
      // from: 发件人信息
      msg.from = params.from;
      // subject: 发送消息主题
      msg.subject = params.subject;
      // body: 发送消息内容
      msg.body = params.body;
      // bodyType: 发送消息内容类型
      msg.bodyType = params.bodyType;
      // silent: 是否采用静默方式发送消息
      msg.silent = params.silent;
      // (function) addAttachment: 添加附件
      // for (let i = 0; i < params.files.length; i++) {
      // 	msg.addAttachment(params.files[i]);
      // }

      plus.messaging.sendMessage(msg, params.success, params.fail);
    }
  },

  // 分享
  share: function (params) {
    if (window.plus) {
      let share;
      plus.share.getServices(e => {
        console.log(JSON.stringify(e));
        params.success(e);
      })
    } else {
      params.fail ? params.fail() : null;
    }

  }
}
